<template>
  <div class="category">
    <!-- 主要内容区域 -->
    <div class="category-content">
      <!-- 左侧一级分类列表 -->
      <div class="main-categories">
        <div class="sidebar-title">全部分类</div>
        <div
          v-for="category in firstLevelCategories"
          :key="category.id"
          class="category-item"
          @mouseenter="handleCategoryMouseEnter(category)"
          @mouseleave="handleCategoryMouseLeave"
          @click="handleCategoryClick(category)"
        >
          <span class="category-name">{{ category.name || category.categoryName || '未命名分类' }}</span>
          <span class="category-arrow">></span>
        </div>
      </div>
      
      <!-- 右侧区域 -->
      <div class="right-section">
        <!-- 二级分类弹窗 -->
        <transition name="slide-down">
          <div
            v-if="showSubcategories && currentCategory"
            class="subcategories-popover"
            @mouseenter="handleSubcategoriesMouseEnter"
            @mouseleave="handleSubcategoriesMouseLeave"
          >
            <div class="subcategories-content">
              <div v-for="subcategory in currentSubcategories" :key="subcategory.id" class="subcategory-item">
                <h3 @click.stop="handleSubcategoryClick(subcategory)">{{ subcategory.name || subcategory.categoryName || '未命名分类' }}</h3>
                <div class="third-level-categories">
                  <span v-for="thirdLevel in getThirdLevelCategories(subcategory.id)" :key="thirdLevel.id" @click.stop="handleThirdLevelCategoryClick(thirdLevel)">
                    {{ thirdLevel.name || thirdLevel.categoryName || '未命名分类' }}
                  </span>
                </div>
              </div>
            </div>
          </div>
        </transition>
        
        <!-- 商品展示区域 -->
        <transition name="fade" v-if="showProducts">
          <div class="products-section">
            <div class="products-header">
              <h2>{{ selectedCategory?.name || selectedCategory?.categoryName || '未命名分类' }} 下的商品</h2>
              <button class="close-btn" @click="showProducts = false">关闭</button>
            </div>
            <div class="products-list">
              <div v-if="categoryProducts.length > 0" class="products-grid">
                <router-link 
                  v-for="product in categoryProducts" 
                  :key="product.id || product.productId"
                  :to="{ name: 'product', params: { id: product.id || product.productId } }"
                  class="product-item"
                >
                  <div class="product-image">
                    <img 
                      :src="product.image || product.img || product.productImage || 'https://via.placeholder.com/200'" 
                      :alt="product.name || product.title || product.productName || '未命名商品'"
                    >
                  </div>
                  <div class="product-info">
                    <h3>{{ product.name || product.title || product.productName || '未命名商品' }}</h3>
                    <p class="product-price">¥{{ product.price !== undefined ? Number(product.price).toFixed(2) : '0.00' }}</p>
                    <p class="product-desc">{{ product.description || product.desc || '暂无描述' }}</p>
                  </div>
                </router-link>
              </div>
              <div v-else class="no-products">
                该分类下暂无商品
              </div>
            </div>
          </div>
        </transition>
      </div>
      
      <!-- 连接区域，用于鼠标在一级分类和二级分类之间移动时保持弹窗显示 -->
      <div
        v-if="showSubcategories && currentCategory"
        class="connection-area"
        @mouseenter="handleSubcategoriesMouseEnter"
        @mouseleave="handleSubcategoriesMouseLeave"
      ></div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { getCategoriesList, getSubcategoriesByParentId } from '../services/categories';
import http from '../services/http';

// 初始化路由
const router = useRouter();

// 分类数据数组
const categories = ref([]);

// 当前选中的一级分类
const currentCategory = ref(null);

// 当前显示的二级分类
const currentSubcategories = ref([]);

// 当前分类下的商品数据
const categoryProducts = ref([]);

// 当前选中的分类信息
const selectedCategory = ref(null);

// 是否显示商品区域
const showProducts = ref(false);

// 是否显示二级分类弹窗
const showSubcategories = ref(false);

// 鼠标是否悬停在一级分类上
const isHoveringCategoryItem = ref(false);

// 鼠标是否悬停在二级分类上
const isHoveringSubcategories = ref(false);

// 计算一级分类
const firstLevelCategories = computed(() => {
  // 筛选出所有一级分类（parentId === 0）
  return categories.value.filter(category => category.parentId === 0);
});

// 根据一级分类ID和sort字段获取关联的二级分类
const getSubcategories = async (categoryId) => {
  try {
    // 获取当前一级分类的完整信息
    const firstLevelCategory = categories.value.find(c => c.id === categoryId);
    if (!firstLevelCategory) {
      console.warn('未找到指定的一级分类:', categoryId);
      return [];
    }
    
    // 获取当前一级分类的sort值（这是用于匹配二级分类的关键）
    const categorySort = typeof firstLevelCategory.sort === 'string' ? parseInt(firstLevelCategory.sort) : firstLevelCategory.sort;
    console.log('一级分类信息:', firstLevelCategory, 'sort值:', categorySort);
    
    // 优先使用本地已有的categories数据进行筛选，避免重复API请求
    let subcategories = categories.value.filter(category => {
      // 确保能处理不同类型的sort值
      const subCategorySort = typeof category.sort === 'string' ? parseInt(category.sort) : category.sort;
      // 确保能处理不同类型的parentId
      const parentId = typeof category.parentId === 'string' ? parseInt(category.parentId) : category.parentId;
      
      // 筛选条件：sort值匹配 且 是二级分类（parentId不为0）
      return subCategorySort === categorySort && parentId !== 0;
    });
    
    // 如果本地数据中没有找到子分类，再尝试从API获取
    if (subcategories.length === 0) {
      console.log('本地数据中未找到子分类，尝试从API获取');
      try {
        const allCategories = await getCategoriesList();
        console.log('API返回的所有分类数量:', allCategories.length);
        
        // 再次根据sort字段筛选二级分类
        subcategories = allCategories.filter(category => {
          const subCategorySort = typeof category.sort === 'string' ? parseInt(category.sort) : category.sort;
          const parentId = typeof category.parentId === 'string' ? parseInt(category.parentId) : category.parentId;
          return subCategorySort === categorySort && parentId !== 0;
        });
      } catch (apiError) {
        console.warn('API获取分类数据失败，但继续使用本地数据:', apiError);
        // 即使API调用失败，也继续使用本地可能存在的数据
      }
    }
    
    console.log('最终筛选的二级分类数量:', subcategories.length);
    return subcategories;
  } catch (error) {
    console.error('获取子分类过程中发生错误:', error);
    // 返回空数组作为保底
    return [];
  }
};

// 获取三级分类
const getThirdLevelCategories = (parentId) => {
  // 从完整的分类数据中筛选三级分类
  // 确保能处理后端返回的不同格式数据
  return categories.value.filter(category => {
    // 有些API返回的可能是字符串类型的ID，需要进行类型转换
    const categoryParentId = typeof category.parentId === 'string' ? parseInt(category.parentId) : category.parentId;
    const targetParentId = typeof parentId === 'string' ? parseInt(parentId) : parentId;
    return categoryParentId === targetParentId;
  });
};

// 处理一级分类点击事件
const handleCategoryClick = async (category) => {
  try {
    console.log('点击一级分类:', category.id, category.name);
    
    // 更新选中的分类信息
    selectedCategory.value = category;
    
    // 使用后端新接口获取一级分类关联的所有商品数据，参数改为sort字段
    const response = await http.get(`/categories/parentCategory/${category.sort}`);
    console.log('后端响应 - 一级分类关联的所有商品数据:', response);
    
    // 处理响应数据
    if (response && typeof response === 'object') {
      // 提取商品列表
      if (Array.isArray(response)) {
        categoryProducts.value = response;
      } else if (response.data && Array.isArray(response.data)) {
        categoryProducts.value = response.data;
      } else if (response.products && Array.isArray(response.products)) {
        categoryProducts.value = response.products;
      } else if (response.list && Array.isArray(response.list)) {
        categoryProducts.value = response.list;
      } else {
        console.warn('商品数据格式不标准，尝试直接使用响应数据:', response);
        categoryProducts.value = [];
      }
    } else {
      console.warn('无效的商品数据响应:', response);
      categoryProducts.value = [];
    }
    
    console.log('从后端获取的商品总数:', categoryProducts.value.length);
    
    // 显示商品区域并隐藏二级分类弹窗
    showProducts.value = true;
    showSubcategories.value = false;
    
    // 可以根据后端返回结果进行后续操作，如页面跳转等
    // 例如：router.push(`/products?categoryId=${category.id}&categoryName=${encodeURIComponent(category.name)}`);
  } catch (error) {
    console.error('获取一级分类商品数据失败:', error);
    categoryProducts.value = [];
    showProducts.value = true;
  }
};

// 处理二级分类点击事件
const handleSubcategoryClick = async (subcategory) => {
  try {
    console.log('点击二级分类:', subcategory.id, subcategory.name);
    
    // 更新选中的分类信息
    selectedCategory.value = subcategory;
    
    // 向后端发送请求，使用正确的API端点获取分类对应的商品数据
    const response = await http.get(`/categories/getproduct/${subcategory.id}`);
    console.log('后端响应 - 二级分类商品数据:', response);
    
    // 处理响应数据
    if (response && typeof response === 'object') {
      // 提取商品列表
      if (Array.isArray(response)) {
        categoryProducts.value = response;
      } else if (response.data && Array.isArray(response.data)) {
        categoryProducts.value = response.data;
      } else if (response.products && Array.isArray(response.products)) {
        categoryProducts.value = response.products;
      } else if (response.list && Array.isArray(response.list)) {
        categoryProducts.value = response.list;
      } else {
        console.warn('商品数据格式不标准，尝试直接使用响应数据:', response);
        categoryProducts.value = [];
      }
    } else {
      console.warn('无效的商品数据响应:', response);
      categoryProducts.value = [];
    }
    
    // 显示商品区域并隐藏二级分类弹窗
    showProducts.value = true;
    showSubcategories.value = false;
    
    // 可以根据后端返回结果进行后续操作，如页面跳转等
    // 例如：router.push(`/products?categoryId=${subcategory.id}&categoryName=${encodeURIComponent(subcategory.name)}`);
  } catch (error) {
    console.error('获取二级分类商品数据失败:', error);
    categoryProducts.value = [];
    showProducts.value = true;
  }
};

// 处理三级分类点击事件
const handleThirdLevelCategoryClick = async (thirdLevelCategory) => {
  try {
    console.log('点击三级分类:', thirdLevelCategory.id, thirdLevelCategory.name);
    
    // 更新选中的分类信息
    selectedCategory.value = thirdLevelCategory;
    
    // 向后端发送请求，使用正确的API端点获取分类对应的商品数据
    const response = await http.get(`/categories/getproduct/${thirdLevelCategory.id}`);
    console.log('后端响应 - 三级分类商品数据:', response);
    
    // 处理响应数据
    if (response && typeof response === 'object') {
      // 提取商品列表
      if (Array.isArray(response)) {
        categoryProducts.value = response;
      } else if (response.data && Array.isArray(response.data)) {
        categoryProducts.value = response.data;
      } else if (response.products && Array.isArray(response.products)) {
        categoryProducts.value = response.products;
      } else if (response.list && Array.isArray(response.list)) {
        categoryProducts.value = response.list;
      } else {
        console.warn('商品数据格式不标准，尝试直接使用响应数据:', response);
        categoryProducts.value = [];
      }
    } else {
      console.warn('无效的商品数据响应:', response);
      categoryProducts.value = [];
    }
    
    // 显示商品区域并隐藏二级分类弹窗
    showProducts.value = true;
    showSubcategories.value = false;
    
    // 可以根据后端返回结果进行后续操作，如页面跳转等
    // 例如：router.push(`/products?categoryId=${thirdLevelCategory.id}&categoryName=${encodeURIComponent(thirdLevelCategory.name)}`);
  } catch (error) {
    console.error('获取三级分类商品数据失败:', error);
    categoryProducts.value = [];
    showProducts.value = true;
  }
};

// 鼠标悬停在一级分类时的处理函数
const handleCategoryMouseEnter = async (category) => {
  // 清除所有未完成的计时器
  clearAllTimeouts();
  
  // 立即设置悬停状态
  isHoveringCategoryItem.value = true;
  
  // 更新当前分类
  currentCategory.value = category;
  
  // 异步获取子分类 - 使用一级分类的sort字段值进行匹配
  currentSubcategories.value = await getSubcategories(category.id);
  
  // 立即显示弹窗（无论是否有子分类）
  showSubcategories.value = true;
};

// 清除所有计时器的函数
const clearAllTimeouts = () => {
  // 清除所有未完成的计时器
  window.clearTimeout(window.categoryMouseLeaveTimeout);
  window.clearTimeout(window.subcategoriesMouseLeaveTimeout);
};

// 鼠标悬停在二级分类或连接区域时的处理函数
const handleSubcategoriesMouseEnter = () => {
  isHoveringSubcategories.value = true;
};

// 鼠标离开一级分类时的处理函数
const handleCategoryMouseLeave = () => {
  isHoveringCategoryItem.value = false;
  // 只有当鼠标既不在一级分类上也不在二级分类上时，才隐藏弹窗
  window.categoryMouseLeaveTimeout = setTimeout(() => {
    if (!isHoveringSubcategories.value) {
      showSubcategories.value = false;
    }
  }, 50);
};

// 鼠标离开二级分类或连接区域时的处理函数
const handleSubcategoriesMouseLeave = () => {
  isHoveringSubcategories.value = false;
  // 只有当鼠标既不在一级分类上也不在二级分类上时，才隐藏弹窗
  window.subcategoriesMouseLeaveTimeout = setTimeout(() => {
    if (!isHoveringCategoryItem.value) {
      showSubcategories.value = false;
    }
  }, 50);
};

// 生成基础的模拟分类数据（仅用于API请求失败时的后备方案）
const generateBasicCategories = () => {
  return [
    { id: 1, name: '电子产品', parentId: 0, sort: 1 },
    { id: 2, name: '服装鞋帽', parentId: 0, sort: 2 },
    { id: 3, name: '家居用品', parentId: 0, sort: 3 },
    { id: 4, name: '手机', parentId: 1, sort: 1 },
    { id: 5, name: '电脑', parentId: 1, sort: 1 },
    { id: 6, name: '耳机', parentId: 1, sort: 1 },
    { id: 7, name: '男装', parentId: 2, sort: 2 },
    { id: 8, name: '女装', parentId: 2, sort: 2 },
    { id: 9, name: '鞋类', parentId: 2, sort: 2 },
    { id: 10, name: '厨房用品', parentId: 3, sort: 3 },
    { id: 11, name: '客厅家具', parentId: 3, sort: 3 },
    { id: 12, name: '卧室用品', parentId: 3, sort: 3 }
  ];
};

// 生成基础的模拟商品数据
const generateBasicProducts = (categoryName) => {
  const baseProducts = [
    { id: 1, name: `${categoryName}商品1`, price: 99.99, image: 'https://via.placeholder.com/200' },
    { id: 2, name: `${categoryName}商品2`, price: 199.99, image: 'https://via.placeholder.com/200' },
    { id: 3, name: `${categoryName}商品3`, price: 299.99, image: 'https://via.placeholder.com/200' },
    { id: 4, name: `${categoryName}商品4`, price: 399.99, image: 'https://via.placeholder.com/200' }
  ];
  return baseProducts;
};

// 从后端获取分类数据
const fetchCategories = async () => {
  try {
    // 尝试调用真实的后端API服务
    const data = await getCategoriesList();
    
    // 确保返回的数据是数组
    if (Array.isArray(data)) {
      categories.value = data;
      
      // 在获取到分类数据后，如果没有选择任何分类，默认选择电子产品分类
      if (!selectedCategory.value && !showProducts.value) {
        // 查找电子产品分类（可能的名称：电子产品、电子数码、电子设备等）
        const electronicsCategory = firstLevelCategories.value.find(cat => {
          if (!cat.name) return false;
          const name = cat.name.toLowerCase();
          return name.includes('电子') || 
                 name.includes('数码') || 
                 name.includes('technology') || 
                 name.includes('electronics');
        });
        
        if (electronicsCategory) {
          // 调用分类点击处理函数，展示电子产品
          await handleCategoryClick(electronicsCategory);
        } else if (firstLevelCategories.value.length > 0) {
          // 如果没有找到电子产品分类，尝试选择第一个一级分类
          const firstCategory = firstLevelCategories.value[0];
          await handleCategoryClick(firstCategory);
        }
      }
    } else {
      console.warn('API返回的数据格式不是数组，使用基础模拟数据');
      // 使用基础模拟数据
      categories.value = generateBasicCategories();
      // 默认选择电子产品分类
      const electronicsCategory = firstLevelCategories.value.find(cat => cat.name === '电子产品');
      if (electronicsCategory) {
        // 直接设置基础商品数据，避免再次调用失败的API
        categoryProducts.value = generateBasicProducts('电子产品');
        selectedCategory.value = electronicsCategory;
        showProducts.value = true;
      }
    }
  } catch (error) {
    console.error('加载分类数据时发生错误:', error);
    // 在API调用失败时（如403权限错误），使用基础模拟数据作为后备方案
    categories.value = generateBasicCategories();
    // 默认选择电子产品分类并显示基础商品数据
    const electronicsCategory = firstLevelCategories.value.find(cat => cat.name === '电子产品');
    if (electronicsCategory) {
      categoryProducts.value = generateBasicProducts('电子产品');
      selectedCategory.value = electronicsCategory;
      showProducts.value = true;
    }
  }
};

// 组件挂载时获取分类数据
onMounted(async () => {
  await fetchCategories();
});
</script>

<style scoped>
/* 主要内容区域样式 */
.category-content {
  display: grid;
  grid-template-columns: 220px 1fr;
  position: relative;
  padding: 20px;
  gap: 0;
}

/* 右侧区域样式 */
.right-section {
  width: 100%;
  min-height: 600px;
  position: relative;
}

/* 二级分类弹窗样式 - 调整为相对于右侧区域定位 */
.subcategories-popover {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  min-height: 400px;
  background: #fff;
  border: 1px solid #e0e0e0;
  border-radius: 0 8px 8px 0;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  padding: 20px;
  margin-left: -20px;
  border-left: none;
}

/* 连接区域样式 - 调整位置 */
.connection-area {
  position: absolute;
  left: -2px;
  top: 0;
  width: 2px;
  height: 100%;
  background-color: transparent;
  z-index: 999;
}

/* 左侧一级分类列表样式 */
.main-categories {
  background: #fff;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
}

.sidebar-title {
  padding: 15px 20px;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  border-bottom: 1px solid #e0e0e0;
}

.category-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  border-bottom: 1px solid #f0f0f0;
  color: #333;
}

.category-item:last-child {
  border-bottom: none;
}

.category-item:hover {
  background-color: #f8f9fa;
  color: #1976d2;
}

.category-name {
  font-size: 15px;
}

.category-arrow {
  font-size: 12px;
  color: #999;
  transition: transform 0.3s ease;
}

.category-item:hover .category-arrow {
  transform: translateX(2px);
  color: #1976d2;
}

/* 滑入动画样式 */
.slide-down-enter-active {
  animation: slideDown 0.3s ease-out;
}

.slide-down-leave-active {
  animation: slideUp 0.3s ease-in;
}

@keyframes slideDown {
  from {
    transform: translateY(-20px);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}

@keyframes slideUp {
  from {
    transform: translateY(0);
    opacity: 1;
  }
  to {
    transform: translateY(-20px);
    opacity: 0;
  }
}

/* 二级分类内容样式 */
.subcategories-content {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
}

.subcategory-item {
  padding: 12px;
  border-radius: 6px;
  transition: background-color 0.3s ease;
}

.subcategory-item:hover {
  background-color: #f9f9f9;
}

.subcategory-item h3 {
  font-size: 16px;
  color: #333;
  margin-bottom: 10px;
}

/* 三级分类样式 */
.third-level-categories {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.third-level-categories span {
  font-size: 14px;
  color: #666;
  cursor: pointer;
  padding: 4px 0;
  transition: color 0.3s ease;
}

.third-level-categories span:hover {
  color: #1976d2;
}

/* 连接区域样式 */
.connection-area {
  position: absolute;
  left: 220px;
  top: 0;
  width: 30px;
  height: 100%;
  background-color: transparent;
  z-index: 999;
}

/* 商品展示区域样式 */
.products-section {
  margin-top: 0;
  width: 100%;
  min-height: 600px;
  background: #fff;
  border: none;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  position: relative;
  z-index: 999;
}

.products-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e0e0e0;
}

.products-header h2 {
  font-size: 18px;
  color: #333;
  margin: 0;
}

.close-btn {
  background: #f5f5f5;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 8px 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.close-btn:hover {
  background: #e0e0e0;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

/* 修改为与首页一致的商品项样式 */
.product-item {
  display: block;
  padding: 12px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
  text-decoration: none;
}

.product-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.product-image {
  height: 160px;
  overflow: hidden;
  background: #f5f5f5;
  border-radius: 6px;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.product-item:hover .product-image img {
  transform: scale(1.05);
}

.product-info {
  padding: 12px 0;
}

.product-info h3 {
  font-size: 14px;
  color: #333;
  margin-bottom: 4px;
  height: 40px;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.product-price {
  color: var(--primary);
  font-weight: 700;
  font-size: 16px;
  margin-bottom: 0;
}

.product-desc {
  font-size: 12px;
  color: #666;
  line-height: 1.4;
  height: 32px;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.no-products {
  text-align: center;
  padding: 60px 20px;
  color: #999;
  font-size: 16px;
}

/* 淡入淡出动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>


